import Express from 'express'
import multer from 'multer'
import path from 'path'
import { ResponseHelper } from './ResponseHelper'
const router = Express.Router()

const storage = multer.diskStorage({
    destination: path.resolve(__dirname, '../../public/upload'),
    filename(req, file, cb) {
        // 文件名
        const time = new Date().getTime()
        const ext = path.extname(file.originalname)
        cb(null, `${time}${ext}`)
    },
})

const allowedExtendsions = [".jpg", '.png', '.gif', '.jpeg']
const upload = multer({
    storage,
    limits: { fileSize: 1024 * 1024 * 5 },
    fileFilter(req, file, cb) {
        // 文件类型
        const ext = path.extname(file.originalname)
        if (allowedExtendsions.includes(ext)) {
            cb(null, true)
        } else {
            return new Error('文件类型不正确')
        }
    }
}).single("imgFile")

router.post("/", (req, res) => {
    upload(req, res, (err) => {
        if (err instanceof multer.MulterError) {
            ResponseHelper.sendError(err.message, res)
        } else {
            const url = '/upload/' + req.file?.filename
            ResponseHelper.sendData(url, res)
        }
    })
})

export default router;